package com.io.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by 41579 on 2016/12/23.
 */
public class NIOServer {
    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();
        SocketAddress sa = new InetSocketAddress("127.0.0.1",1000);
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(sa);
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        while(true){
            Thread.sleep(2000);
            int i = selector.select();
            System.out.println(i+"selector select()");
            if(i==0){
                continue;
            }
            Set<SelectionKey> keys = selector.selectedKeys();
            System.out.println(keys.size());
            Iterator<SelectionKey> iter = keys.iterator();
            while(iter.hasNext())
            {
                SelectionKey key1 = iter.next();
                if(key1.isAcceptable()) {
                    System.out.println("Acceptable.....");
                    iter.remove();
                }
                //iter.remove();
            }
            System.out.println(keys.size());

        }
    }
}
